<template>
  <suspense>
    
    <router-view v-slot="{ Component }" >
      <keep-alive>
        <component :is="Component" :key="$route.path" v-if="$route.meta.isKeepAlive"/>
      </keep-alive>
      <component :is="Component" :key="$route.path" v-if="!$route.meta.isKeepAlive"/>
    </router-view>
  </suspense>

  <Overlay :show="store.state.isLoading" class-name="my-overlay">
    <Loading class="loading" color="#fff" size="32px" vertical>
      加载中...
    </Loading>
  </Overlay>
</template>

<script setup>
import { Loading, Overlay } from 'vant'
import { useStore } from 'vuex'

const store = useStore()

const user = JSON.parse(localStorage.getItem('user'))
store.commit('setUser', user)

const token = localStorage.getItem('token')
store.commit('setToken', token)

let cart = JSON.parse(localStorage.getItem('cart'))
if (!cart) cart = []
cart.forEach(item => {
  store.commit('addGoods2cart', item)
})

window.addEventListener('beforeunload', () => {
  //持久化存储user
  localStorage.setItem('user', JSON.stringify(store.state.user))
  //持久化存储token
  localStorage.setItem('token', store.state.token)
  //持久化存储cart
  localStorage.setItem('cart', JSON.stringify(store.state.cart))
})
</script>

<style lang="less" scoped>
.my-overlay {
  background-color: transparent;

  .loading {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: rgba(0, 0, 0, .7);
    height: 100px;
    width: 85px;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 6px;
  }
}
</style>
